package com.jxlc.web.api.system.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.jxlc.common.constant.Constants;
import com.jxlc.common.constant.RedisConst;
import com.jxlc.common.constant.UserConstants;
import com.jxlc.common.core.domain.entity.SysUser;
import com.jxlc.common.core.domain.model.LoginBody;
import com.jxlc.common.core.domain.model.LoginUser;
import com.jxlc.common.core.domain.model.SysAuthBody;
import com.jxlc.common.core.redis.TokenRedisCache;
import com.jxlc.common.enums.UserStatus;
import com.jxlc.common.exception.GlobalException;
import com.jxlc.common.exception.base.BaseException;
import com.jxlc.common.exception.user.*;
import com.jxlc.common.utils.DateUtils;
import com.jxlc.common.utils.MessageUtils;
import com.jxlc.common.utils.SecurityUtils;
import com.jxlc.common.utils.StringUtils;
import com.jxlc.common.utils.ip.IpUtils;
import com.jxlc.framework.manager.AsyncManager;
import com.jxlc.framework.manager.factory.AsyncFactory;
import com.jxlc.framework.oauth2.domain.OAuth2AccessToken;
import com.jxlc.framework.oauth2.domain.OAuth2RefreshToken;
import com.jxlc.framework.web.service.SysTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 登录校验方法
 * 
 * @author jxlc
 */
@Slf4j
@Component
public class SysLoginService
{
    @Resource
    private SysTokenService sysTokenService;

    @Resource
    private ISysUserService userService;

    @Resource
    private TokenRedisCache tokenRedisCache;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private ISysConfigService configService;

    /**
     * 登录验证
     */
    public SysAuthBody login(LoginBody loginBody)
    {
        String uuid = loginBody.getUuid();
        String username = loginBody.getUsername();
        if (configService.selectCaptchaEnabled()) {
            validCaptcha(uuid, username, loginBody.getCode());
        }
        // 登录前置校验
        loginPreCheck(username, loginBody.getPassword());
        return createAuthBody(username, loginBody.getPassword());
    }
    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**校验验证码*/
    private void validCaptcha(String uuid, String username, String code){
        String verifyKey = RedisConst.CAPTCHA_CODE_KEY + uuid;
        String captcha = tokenRedisCache.getVerifyKey(verifyKey);
        tokenRedisCache.delVerifyKey(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,
                    Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!captcha.equalsIgnoreCase(code)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,
                    Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**获取权限信息*/
    private SysAuthBody createAuthBody(String username, String pwd){
        SysUser user = this.loadSysUser(username);
        if (!SecurityUtils.matchesPassword(pwd, user.getPassword())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,
                    Constants.LOGIN_FAIL,MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username,
                Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        //缓存对象value
        LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
        loginUser.setRoles(permissionService.getRolePermission(user));
        // 生成刷新令牌
        OAuth2RefreshToken refreshToken = sysTokenService.createRefreshToken(user.getUserId());
        loginUser.setLoginType(refreshToken.getLoginType());
        //生成访问令牌
        OAuth2AccessToken token = sysTokenService.createAccessToken(refreshToken, loginUser);
        Assert.notNull(token, "token创建失败");
        //获取登录人访问ip
        return new SysAuthBody(token.getAccessToken(), token.getExpiresTime());
    }

    /**
     * 获取用户信息
     */
    public SysUser loadSysUser(String username) throws UsernameNotFoundException {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BaseException("对不起，您的账号：" + username + " 已停用");
        }
        if (user.getDept().getAncestors() == null) {
            throw new GlobalException("用户行政区划不存在，请联系管理员");
        }
        return user;
    }

    /**
     * 获取登录用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        String token = sysTokenService.getHeaderToken(request);
        Assert.notNull(token, "token不存在");
        if (sysTokenService.hasSysTokenCache(token)) {
            return sysTokenService.getSysTokenCache(token);
        }
        //数据库查询用户访问令牌信息
        OAuth2AccessToken accessToken = sysTokenService.getAccessToken(token);
        Assert.notNull(accessToken, "token校验失败");
        if (DateUtils.isExpired(accessToken.getExpiresTime())) {
            throw new GlobalException("token已过期");
        }
        SysUser user = userService.selectUserById(accessToken.getUserId());
        Assert.notNull(user, "用户不存在");

        //构建缓存对象value
        LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
        loginUser.setRoles(permissionService.getRolePermission(user));
        //如果在 MySQL 存在，则往 Redis 中写入
        Integer expireTime = Math.toIntExact(LocalDateTimeUtil.between(LocalDateTime.now(), accessToken.getExpiresTime(), ChronoUnit.SECONDS));
        sysTokenService.setSysTokenCache(accessToken.getAccessToken(), loginUser, expireTime);
        return loginUser;
    }
}
